<template>
  <div>
    <a-input ref="user_input" :disabled="disabled" :value="departName" :readOnly="true" @focus="handleClick" placeholder="请选择部门"/>
    <a-modal
      title="选择部门"
      :visible="visible"
      :width="800"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-input-search
        v-model="queryParam.departName"
        @search="searchQuery"
        placeholder="请输入部门名称进行筛选"
        style="margin-bottom:10px;"
        />
      <a-tree
        checkable
        :checkStrictly="true"
        v-model="checkedKeys"
        :tree-data="treeData"
        @check="onCheck"
      />
    </a-modal>
  </div>
</template>
<script>
import { getAction } from '@/api/manage'
export default {
  name: 'Dept',
  props: ['record', 'value', 'disabled'],
  data() {
    return {
      visible: false,
      queryParam: {
        departName: ''
      },
      url: {
        list: '/sys/sysDepart/queryTreeList',
        queryList: '/sys/sysDepart/searchBy',
        getDepartName: 'sys/sysDepart/getDepartName'
      },
      treeData: [],
      checkedKeys: [],
      checkNode: '',
      departName: '',
      notGetDepartName: false
    }
  },
  watch: {
    value(newValue) {
      if (newValue) {
        !this.notGetDepartName && this.getDepartName(newValue)
      } else {
        this.departName = ''
      }
    }
  },
  methods: {
    handleClick() {
      this.loadTreeData()
      this.$refs.user_input.blur()// 取消输入框焦点 解决弹窗重复bug
      this.visible = true
    },
    handleOk() {
      if (this.checkNode) {
        this.$emit('change', this.checkNode.data.props.orgCode)
        this.departName = this.checkNode.data.props.departName
        this.notGetDepartName = true
      } else {
        this.$emit('change', '')
      }
      this.visible = false
    },
    handleCancel() {
      this.visible = false
    },
    onCheck(selectedKeys, e) { // 只选中一个
      this.checkedKeys = [selectedKeys.checked.pop()]
      this.checkNode = e.checkedNodes.pop()
    },
    loadTreeData(param) {
      getAction(this.url.list).then(res => {
        if (res.success) {
          this.treeData = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },
    searchQuery() {
      getAction(this.url.queryList, { keyWord: this.queryParam.departName }).then(res => {
        if (res.success) {
          this.treeData = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getDepartName(orgCode) { // 根据username获取realname
      const that = this
      getAction(this.url.getDepartName, { orgCode: orgCode }).then(function(res) {
        that.departName = res.result && res.result.departName
      }).catch((error) => {
        console.log(error)
      })
    }
  },
  mounted() {

  }
}
</script>
